package services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import entites.Utilisateur;

public class GestionUtilisateur {
	Connection con = null;

	public GestionUtilisateur() {
	}

	public void connect() throws ClassNotFoundException, SQLException {
		Class.forName("org.postgresql.Driver");
		String url = "jdbc:postgresql://sqlserv/da2i";
		String user = "ricqh";
		String pass = "moi";
		con = DriverManager.getConnection(url, user, pass);

	}

	public void close() throws SQLException {
		con.close();
	}

	public void creer(Utilisateur ut) throws SQLException,
			ClassNotFoundException {
		connect();
		String query = "insert into utilisateur (login,mdp,role) values(?,?,?)";
		PreparedStatement pstmt = con.prepareStatement(query);
		pstmt.setString(1, ut.getLogin());
		pstmt.setString(2, ut.getMdp());
		pstmt.setString(3, ut.getRole());
		pstmt.executeUpdate();
		close();
	}

	public void supprimer(Utilisateur ut) throws SQLException,
			ClassNotFoundException {
		connect();
		String query = "delete from utilisateur where login=?";
		PreparedStatement pstmt = con.prepareStatement(query);
		pstmt.setString(1, ut.getLogin());
		pstmt.executeUpdate();
		close();
	}

	public String modifier(Utilisateur ut1) throws SQLException {
		try {
			connect();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String str = "";
		String query = "update utilisateur set login=?,mdp=?,role=? where idUser=?";
		PreparedStatement pstmt = con.prepareStatement(query);
		pstmt.setString(1, ut1.getLogin());
		pstmt.setString(2, ut1.getMdp());
		pstmt.setString(3, ut1.getMdp());
		pstmt.setInt(4, ut1.getIdUser());
		int i = 0;
		try {
			i = pstmt.executeUpdate();
		} catch (Exception e) {
			str += e.getMessage();
		}

		if (i == 0) {
			str += " Modification non effectuée";
		} else {
			str = "Modification effectuée avec succès";
		}

		close();
		return str;
	}

	public String affecter(Utilisateur ut, String role) throws SQLException {
		try {
			connect();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String str = "";
		String query = "update utilisateur set role=? where idUser=?";
		PreparedStatement pstmt = con.prepareStatement(query);
		pstmt.setString(1, role);
		pstmt.setInt(2, ut.getIdUser());
		int i = 0;
		try {
			i = pstmt.executeUpdate();
		} catch (Exception e) {
			str += e.getMessage();
		}

		if (i == 0) {
			str += " Modification non effectuée";
		} else {
			str = " Modification effectuée avec succès";
		}

		close();
		return str;
	}

}
